package com.leetcode.联赛.力扣杯春季编程大赛;

import java.util.PriorityQueue;

/**
 * @author: xiaomi
 * @date: 2021/4/5
 * @description: 3. 魔塔游戏
 */
public class B_3_魔塔游戏 {
    static B_3_魔塔游戏 action = new B_3_魔塔游戏();

    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }

    static void test1() {
        //
        int[] nums = new int[]{100, 100, 100, -250, -60, -140, -50, -50, 100, 150};
        int res = action.magicTower(nums);
        System.out.println("res = " + res);
    }

    static void test2() {
        //

        //System.out.println("res = " + res);
    }

    static void test3() {
        //

        //System.out.println("res = " + res);
    }

    public int magicTower(int[] nums) {
        //check
        int len = nums.length;
        long sum = 0;
        for (int i = 0; i < len; i++) {
            sum += nums[i];
        }
        if (sum < 0) {
            return -1;
        }
        //
        long tempSum = 0;
        int count = 0;
        //做一个大顶堆
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        long heapSum = 0;
        for (int i = 0; i < len; i++) {
            if (nums[i] < 0) {
                heapSum -= nums[i];
                heap.add(nums[i]);
                while (tempSum < heapSum && !heap.isEmpty()) {
                    Integer remove = heap.remove();
                    heapSum += remove;
                    count++;
                }
            } else {
                tempSum += nums[i];
            }
        }
        return count;
    }
}
